﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoAddonBiz_FreightForwarder.Cost.Bo
{
    class CreateOrder
    {
        private SAPbobsCOM.Documents Order;

        public SAPbobsCOM.Company SBOCompany { get; set; }
        public SAPbobsCOM.Recordset ors { get; set; }
        public OrderLines OrderLines { get; set; }

        /// <summary>
        /// 处理订单
        /// </summary>
        /// <returns></returns>
        public bool HanldeOrder()
        {
            try
            {
                if (SBOCompany.InTransaction == false) SBOCompany.StartTransaction();
                foreach (OrderLine line in OrderLines)
                {
                    if (string.IsNullOrEmpty(line.BoType) || line.BoEntry <= 0 || string.IsNullOrEmpty(line.BoSerialNum))
                    {
                        throw (new Exception("业务类型不能为空，请检查录入的费用。"));
                    }

                    if (line.OrderType == OrderType.SalesOrder)
                    {
                        Order = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders);
                    }
                    else
                    {
                        Order = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseOrders);
                    }
                    switch (line.Status)
                    {
                        case Status_Line.Add:
                            add(line);
                            break;
                        case Status_Line.del:
                            delete(line);
                            OrderLines.Delete(line);//从对象列表中删除此行（实际上是在此行数据上添加标识-1111）。
                            OrderLines.UpdateVisOrder();
                            break;
                        case Status_Line.Fixed:
                            Fix(line);
                            break;
                    }
                }
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
                return true;
            }
            catch (Exception ex)
            {
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                throw ex;
            }
        }
        private void add(OrderLine line)
        {
            string SQL = string.Empty;
            if (line.OrderType == OrderType.SalesOrder)
            {
                SQL = @"
                        SELECT T0.DocEntry
                        FROM ORDR T0
	                        INNER JOIN RDR1 T1 ON T0.DocEntry = T1.DocEntry
                        Where T0.DocStatus = 'O' And T0.CANCELED = 'N' And T0.CardCode = '{0}' And T1.U_BoType = '{1}' And T1.U_BoEntry = '{2}'	
                        Group by T0.DocEntry
                       ";
            }
            else
            {
                SQL = @"
                        SELECT T0.DocEntry
                        FROM OPOR T0
	                        INNER JOIN POR1 T1 ON T0.DocEntry = T1.DocEntry
                        Where T0.DocStatus = 'O' And T0.CANCELED = 'N' And T0.CardCode = '{0}' And T1.U_BoType = '{1}' And T1.U_BoEntry = '{2}'	
                        Group by T0.DocEntry
                       ";
            }
            ors.DoQuery(string.Format(SQL, line.CardCode, line.BoType, line.BoEntry));
            if (ors.RecordCount > 0)
            {
                if (Order.GetByKey(ors.Fields.Item("DocEntry").Value))
                {
                    Order.ShipToCode = string.Empty;/*added by WangPeng 2012-7-11 防止客户的收货方地址编码更改引发的异常*/
                    Order.Lines.Add();
                    line.VisOrder = Order.Lines.Count;
                    SetOrderLine(line);
                    int rtnCode = Order.Update();
                    if (rtnCode != 0)
                    {
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
                        throw new Exception(SBOCompany.GetLastErrorDescription());
                    }
                }
            }
            else
            {
                Order.CardCode = line.CardCode;
                Order.DocDate = DateTime.Now;
                Order.DocDueDate = DateTime.Now;
                Order.DocCurrency = "RMB";
                Order.ShipToCode = "";
                SetOrderLine(line);
                if (Order.Add() != 0)
                {
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
                    string ErrMsg = string.Empty;
                    if (SBOCompany.GetLastErrorCode() == -5002)
                    {
                        if (line.OrderType == OrderType.SalesOrder)
                        {
                            ErrMsg = "“" + line.CardName + "” 在业务伙伴 客户 中没有添加，请添加业务伙伴后再执行此操作。\r\n";
                        }
                        if (line.OrderType == OrderType.Purchase)
                        {
                            ErrMsg = "“" + line.CardName + "” 在业务伙伴 供应商 中没有添加，请添加业务伙伴后再执行此操作。\r\n";
                        }
                    }
                    throw new Exception(ErrMsg + SBOCompany.GetLastErrorCode().ToString() + " -- " + SBOCompany.GetLastErrorDescription());
                }
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
        }
        /// <summary>
        /// 删除费用
        /// </summary>
        /// <param name="line"></param>
        private void delete(OrderLine line)
        {
            if (Order.GetByKey(line.DocEntry))
            {
                Order.Lines.SetCurrentLine(line.VisOrder - 1);
                Order.Lines.Delete();
                Order.Lines.SetCurrentLine(0);
                if (string.IsNullOrEmpty(Order.Lines.ItemCode))
                {
                    if (Order.Cancel() != 0)
                    {
                        throw new Exception(SBOCompany.GetLastErrorDescription());
                    }
                }
                else
                    if (Order.Update() != 0)
                    {
                        throw new Exception(SBOCompany.GetLastErrorDescription());
                    }
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
        }
        private void Fix(OrderLine line)
        {
            if (Order.GetByKey(line.DocEntry))
            {
                SetOrderLine(line);
                int RtnCode = Order.Update();
                if (RtnCode != 0)
                {
                    throw new Exception(SBOCompany.GetLastErrorDescription());
                }
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
            }
        }
        private void SetOrderLine(OrderLine line)
        {
            Order.Lines.SetCurrentLine(line.VisOrder - 1);
            Order.Lines.ItemCode = line.ItemCode;
            Order.Lines.Quantity = line.Quantity * (1 + line.TaxRate);
            Order.Lines.BarCode = line.CodeBars;
            //Order.Lines.PriceAfterVAT = line.Price;
            //Order.Lines.Price = line.Price;
            Order.Lines.UnitPrice = line.Price;
            Order.Lines.DiscountPercent = 0d;

            Order.Lines.Currency = line.Currency;//币种
            Order.Lines.Rate = double.Parse(line.Rate);//汇率
            Order.Lines.ShipDate = line.PaPayDate;
            Order.Lines.FreeText = line.FreeTxt;
            Order.Lines.TaxCode = "";
            Order.Lines.VatGroup = "";
            Order.Lines.ShipToCode = string.Empty;/*added by WangPeng 2012-7-11 防止客户的收货方地址编码更改引发的异常*/
            #region 自定义字段赋值
            Order.Lines.UserFields.Fields.Item("U_Enterman").Value = line.Enterman;
            Order.Lines.UserFields.Fields.Item("U_EnterDate").Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            Order.Lines.UserFields.Fields.Item("U_IsCheck").Value = line.IsCheck;
            Order.Lines.UserFields.Fields.Item("U_CheckDate").Value = line.CheckDate;
            Order.Lines.UserFields.Fields.Item("U_Checker").Value = line.Checker;
            Order.Lines.UserFields.Fields.Item("U_BillNumber").Value = line.BillNumber;
            Order.Lines.UserFields.Fields.Item("U_UnitMeasure").Value = line.UnitMeasure;
            Order.Lines.UserFields.Fields.Item("U_IsShowTax").Value = line.IsShowTax;
            Order.Lines.UserFields.Fields.Item("U_BoType").Value = line.BoType;
            Order.Lines.UserFields.Fields.Item("U_BoEntry").Value = line.BoEntry;
            Order.Lines.UserFields.Fields.Item("U_BoSerialNum").Value = line.BoSerialNum;
            Order.Lines.UserFields.Fields.Item("U_Cashier").Value = line.Cashier;//收款负责人
            Order.Lines.UserFields.Fields.Item("U_TaxRate").Value = line.TaxRate;//税率
            #endregion

        }
    }
}
